package com.example.chuntiao.cophook.ui;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.signature.ObjectKey;
import com.example.chuntiao.cophook.R;
import com.example.chuntiao.cophook.enums.UpdateState;
import com.example.chuntiao.cophook.exception.NewUserException;
import com.example.chuntiao.cophook.mytools.HttpTool;
import com.example.chuntiao.cophook.mytools.MyApp;
import com.example.chuntiao.cophook.mytools.PhoneTool;

import java.io.IOException;

public class MyInfoActivity extends AppCompatActivity {

    static final int REQ_FOR_PHOTO_ACTI = 0;
    static final int REQ_FOR_LOGIN_ACTI = 1;

    LinearLayout photoLayout;
    LinearLayout nameLayout;
    LinearLayout phone1Layout;
    LinearLayout phone2Layout;
    LinearLayout locateLayout;

    LinearLayout modiPass;
    LinearLayout reLogin;
    ImageView imgPhoto;
    MyApp mApp;

    TextView txtName;
    TextView txtPhone1;
    TextView txtPhone2;
    TextView txtLocate;
    Boolean[] changed = new Boolean[]{false};

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQ_FOR_PHOTO_ACTI:
                if (resultCode == RESULT_OK) {
                    int imgVer = data.getIntExtra("img_ver", -1);

                    SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
                    editor.putInt("img_ver", imgVer);
                    editor.apply();

                    Glide.with(MyInfoActivity.this).load(MyApp.HOST_URL + "image/" + "u_" + mApp.getUid())
                            .apply(RequestOptions.signatureOf(new ObjectKey(imgVer))).into(imgPhoto);
                    mApp.setImgVer(imgVer);
                    changed[0] = true;
                }
                break;
            case REQ_FOR_LOGIN_ACTI:
                if (resultCode == RESULT_OK) {
                    refreshViews(data);
                    setResult(RESULT_OK, data);
                }
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_info);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        mApp = (MyApp) getApplication();

        setTitle("我的");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        photoLayout = (LinearLayout) findViewById(R.id.photo_layout);
        nameLayout = (LinearLayout) findViewById(R.id.name_layout);
        phone1Layout = (LinearLayout) findViewById(R.id.phone1_layout);
        phone2Layout = (LinearLayout) findViewById(R.id.phone2_layout);
        locateLayout = (LinearLayout) findViewById(R.id.locate_layout);
        modiPass = (LinearLayout) findViewById(R.id.layout_modi_pass);
        reLogin = (LinearLayout) findViewById(R.id.layout_reLogin);

        imgPhoto = (ImageView) findViewById(R.id.img_photo);
        txtName = (TextView) findViewById(R.id.txt_name11);
        txtPhone1 = (TextView) findViewById(R.id.txt_phone1);
        txtPhone2 = (TextView) findViewById(R.id.txt_phone2);
        txtLocate = (TextView) findViewById(R.id.txt_locate111);


        photoLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MyInfoActivity.this, PhotoActivity.class);
                startActivityForResult(intent, REQ_FOR_PHOTO_ACTI);
            }
        });


        nameLayout.setOnClickListener(new View.OnClickListener() {
            InputDialog dialog=new InputDialog(MyInfoActivity.this,"姓名",txtName,changed);
            @Override
            public void onClick(View v) {
                dialog.setText(txtName.getText());
                dialog.setSelection(txtName.length());
                dialog.show();
            }
        });


        final InputDialog phone1Input=new InputDialog(MyInfoActivity.this,"电话1",txtPhone1,changed,InputType.TYPE_CLASS_PHONE);
        phone1Input.setListener(new InputDialog.OnPositiveListener() {
            @Override
            public void onPositiveClick() {

                if (ContextCompat.checkSelfPermission(MyInfoActivity.this, Manifest.permission.CALL_PHONE)
                        == PackageManager.PERMISSION_GRANTED) {
                    String newImsi = PhoneTool.getImsi(MyInfoActivity.this);
                    if(!newImsi.equals(mApp.getImsi())) {
                        SharedPreferences.Editor editor=getSharedPreferences("data",MODE_PRIVATE).edit();
                        editor.putString("imsi", newImsi);
                        editor.apply();
                        mApp.setImsi(newImsi);
                    }

                }
            }
        });
        phone1Layout.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                phone1Input.setText(txtPhone1.getText());
                phone1Input.setSelection(txtPhone1.length());
                phone1Input.show();
            }
        });

        phone2Layout.setOnClickListener(new View.OnClickListener() {
            InputDialog dialog=new InputDialog(MyInfoActivity.this,"电话2",txtPhone2,changed,InputType.TYPE_CLASS_PHONE);
            @Override
            public void onClick(View v) {
                dialog.setText(txtPhone2.getText());
                dialog.setSelection(txtPhone2.length());
                dialog.show();
            }
        });

        locateLayout.setOnClickListener(new View.OnClickListener() {
            InputDialog dialog=new InputDialog(MyInfoActivity.this,"地址",txtLocate,changed);

            @Override
            public void onClick(View v) {
                dialog.setText(txtLocate.getText());
                dialog.setSelection(txtLocate.length());
                dialog.show();
            }
        });


        final InputDialog smsDialog=new InputDialog(MyInfoActivity.this,"身份确认","请输入你曾经注册过的手机号");
        smsDialog.setListener(new InputDialog.OnPositiveListener() {
            @Override
            public void onPositiveClick() {
                final String phone=smsDialog.getString();
                new AsyncTask<Void,Void,Void>(){
                    AlertDialog alertDialog = null;
                    ProgressDialog progressDialog = null;
                    boolean hasPhone=true;
                    boolean reqSucc=false;
                    @Override
                    protected void onPreExecute() {
                        progressDialog=ProgressDialog.show(MyInfoActivity.this,"稍后","正在检查身份并发送验证码");
                        alertDialog = new AlertDialog.Builder(MyInfoActivity.this)
                                .setMessage("发送失败，未知错误。")
                                .setPositiveButton(R.string.yse, null)
                                .create();
                    }

                    @Override
                    protected Void doInBackground(Void... params) {

                        try {
                            reqSucc=HttpTool.reqSms(MyInfoActivity.this,phone);
                        }catch (NewUserException e){
                            alertDialog.setMessage("发送失败，数据库未找到您的phone!");
                            hasPhone=false;
                        }
                        catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void aVoid) {
                        progressDialog.dismiss();
                        if(!hasPhone || !reqSucc){
                            alertDialog.show();
                        }else {
                            alertDialog=null;//开启一个新的界面来输入验证码
                            Intent intent=new Intent(MyInfoActivity.this,InputCheckNumActivity.class);
                            startActivity(intent);
                        }
                    }

                }.execute();
            }
        });
        modiPass.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                smsDialog.show();
            }
        });

        reLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MyInfoActivity.this, LogInActivity.class);
                startActivityForResult(intent, REQ_FOR_LOGIN_ACTI);
            }
        });

        refreshViews();
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case android.R.id.home:
                this.onBackPressed();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        Log.d("android.R.id.home:", "run: ++++++++++++++++++++++++++++++++++++++++++++++++++++");
        if (changed[0]) {
            updateData();
        }
        super.onBackPressed();
    }

    void updateData() {
        final String name = txtName.getText().toString();
        final String phone1 = txtPhone1.getText().toString();
        final String phone2 = txtPhone2.getText().toString();
        final String locate = txtLocate.getText().toString();

        new Thread() {
            @Override
            public void run() {

                if (ContextCompat.checkSelfPermission(MyInfoActivity.this, Manifest.permission.CALL_PHONE)
                        == PackageManager.PERMISSION_GRANTED) {
                    final String imsi=PhoneTool.getImsi(MyInfoActivity.this);
                    mApp.setImsi(imsi);
                    SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
                    editor.putString("imsi", imsi);
                    editor.apply();
                }


                try {
                    UpdateState sate = HttpTool.sendOkHttpUpDatePersonInfo(
                            MyInfoActivity.this,
                            name,
                            phone1,
                            phone2,
                            locate
                    );
                    if (sate == UpdateState.FAIL)
                        mApp.getMainHandler().sendEmptyMessage(MainActivity.HANDEL_MSG_UPDATE_WRONG);
                    else {


                        SharedPreferences.Editor editor = getSharedPreferences("data", MODE_PRIVATE).edit();
                        editor.putString("uname", name);
                        editor.putString("phone1", phone1);
                        editor.putString("phone2", phone2);
                        editor.putString("locate", locate);

                        editor.commit();

                        mApp.setUname(name);
                        mApp.setPhone1(phone1);
                        mApp.setPhone2(phone2);
                        mApp.setLocate(locate);

                        final Bundle bundle = new Bundle();
                        bundle.putString("uname", name);
                        bundle.putString("phone1", phone1);
                        bundle.putString("uid", mApp.getUid());
                        bundle.putInt("img_ver", mApp.getImgVer());
                        Message msg = Message.obtain();
                        msg.setData(bundle);
                        msg.what = MainActivity.HANDEL_MSG_UPDATE_OK;
                        mApp.getMainHandler().sendMessage(msg);
                    }

                } catch (IOException e) {
                    mApp.getMainHandler().sendEmptyMessage(MainActivity.HANDEL_MSG_UPDATE_WRONG);
                }
            }
        }.start();
    }


    void refreshViews() {
        txtLocate.setText(mApp.getLocate());
        txtName.setText(mApp.getUname());
        txtPhone1.setText(mApp.getPhone1());
        txtPhone2.setText(mApp.getPhone2());
        if (mApp.getImgVer() != -1)
            Glide.with(MyInfoActivity.this).load(MyApp.HOST_URL + "image/" + "u_" + mApp.getUid())
                    .apply(RequestOptions.signatureOf(new ObjectKey(mApp.getImgVer()))).into(imgPhoto);
    }

    void refreshViews(Intent intent) {
        txtLocate.setText(intent.getStringExtra("locate"));
        txtName.setText(intent.getStringExtra("uname"));
        txtPhone1.setText(intent.getStringExtra("phone1"));
        txtPhone2.setText(intent.getStringExtra("phone2"));
        if (mApp.getImgVer() != -1)
            Glide.with(MyInfoActivity.this).load(MyApp.HOST_URL + "image/" + "u_" + intent.getStringExtra("uid"))
                    .apply(RequestOptions.signatureOf(new ObjectKey(intent.getIntExtra("img_ver", -1)))).into(imgPhoto);
    }
}
